<template>
  <div>
    <div class="card px-3 pt-3 mb-3">
      <el-form @submit.native.prevent :inline="true">
        <el-form-item>
          <el-date-picker
            v-model="formData.dateRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            unlink-panels
            @change="handleQuery"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <select-address
            v-model="queryParams.addressCode"
            placeholder="地址查询"
            auto-top
            clearable
            :bottom-level="2"
            @change="handleQuery"
          ></select-address>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" icon="el-icon-search" @click="getData()">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card p-3 mb-3">
      <div class="analy-title">金额统计分析</div>
      <div class="w-100">
        <el-echarts
          theme="macarons"
          :loading="loading"
          :height="480"
          :option="chartOption"
          @onInit="handleChartInit"
        ></el-echarts>
      </div>
    </div>

    <div class="card p-3">
      <div class="d-flex justify-content-between mb-3">
        <div class="analy-title">项目详情数据</div>

        <div class="d-flex">
          <el-radio-group class="anylay-type-radio mr-3" v-model="projectType">
            <el-radio-button
              v-for="(type, index) in enumProjectType"
              :key="index"
              :label="type.value"
            >
              <span class="mx-3">{{ type.label }}</span>
              <!-- <span>{{type.count}}</span> -->
            </el-radio-button>
          </el-radio-group>
          <el-button
            :loading="downloadLoading"
            type="text"
            icon="el-icon-download"
            @click="exportExcel()"
          >
            下载{{ projectTypeLabel }}项目
          </el-button>
        </div>
      </div>

      <div v-show="projectType === 0">
        <div class="mb-3" v-if="inProjectSearch">
          <span>当前查询：</span>
          <el-tag closable type="primary" @close="handleSearchClose(0)">
            {{ inProjectSearch }}
          </el-tag>
        </div>
        <analy-list ref="listRef0" :query-params="inQueryParams"></analy-list>
      </div>
      <div v-show="projectType === 1">
        <div class="mb-3" v-if="outProjectSearch">
          <span class="text-muted">当前查询：</span>
          <el-tag closable type="primary" @close="handleSearchClose(1)">
            {{ outProjectSearch }}
          </el-tag>
        </div>
        <analy-list ref="listRef1" :query-params="outQueryParams"></analy-list>
      </div>
      <div v-show="projectType === 2">
        <div class="mb-3" v-if="newProjectSearch">
          <span>当前查询：</span>
          <el-tag closable type="primary" @close="handleSearchClose(2)">
            {{ newProjectSearch }}
          </el-tag>
        </div>
        <analy-list ref="listRef2" :query-params="newQueryParams"></analy-list>
      </div>
      <div v-show="projectType === 3">
        <div class="mb-3" v-if="comProjectSearch">
          <span>当前查询：</span>
          <el-tag closable type="primary" @close="handleSearchClose(3)">
            {{ comProjectSearch }}
          </el-tag>
        </div>
        <analy-list ref="listRef2" :query-params="comQueryParams"></analy-list>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMonthLastDayDate } from '@/common/plugins/tools/date'
import { enumProjectType, getParams } from './reportMixins'

import SelectAddress from '@/components/select/SelectAddress'
import AnalyList from '@/credit/views/city/report/AnalyList'

export default {
  components: {
    SelectAddress,
    AnalyList,
  },
  props: {},
  data() {
    return {
      loading: false,
      downloadLoading: false,
      formData: {
        dateRange: [],
      },
      queryParams: {
        clientId: '',
        addressCode: '',
        startDate: '',
        endDate: '',
        bankCode: '',
        busStatus: '',
        guaType: '1,2,3,4',
      },

      chart: {},
      chartOption: {},

      enumProjectType: [...enumProjectType, { value: 3, label: '代偿', count: 0 }],
      projectType: 0,
      inProjectSearch: '',
      outProjectSearch: '',
      newProjectSearch: '',
      comProjectSearch: '',
      inProjectFunds: -1,
      outProjectFunds: -1,
      newProjectFunds: -1,
      comProjectFunds: -1,
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    projectTypeLabel() {
      const item = enumProjectType.find(it => it.value === this.projectType)
      return item ? item.label : ''
    },
    inQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 0,
        fundsType: this.inProjectFunds,
      }
    },
    outQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 1,
        fundsType: this.outProjectFunds,
      }
    },
    newQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 2,
        fundsType: this.newProjectFunds,
      }
    },
    comQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 3,
        fundsType: this.comProjectFunds,
      }
    },
  },
  watch: {},
  created() {
    this.setDateParams()
    this.getData()
  },
  mounted() {},
  methods: {
    setDateParams(date = new Date()) {
      const year = date.getFullYear()
      const month = date.getMonth()
      const start = new Date(year, 0, 1)
      const end = getMonthLastDayDate(year, month)

      this.formData.dateRange = [start, end]
      this.queryParams.startDate = start
      this.queryParams.endDate = end
      this.queryParams.clientId = this.clientId
    },
    listGetData() {
      const { listRef } = this.$refs
      if (listRef) {
        listRef.getData()
      }
      this.getData()
    },
    exportExcel() {
      const listRef = this.$refs[`listRef${this.projectType}`]
      if (listRef) {
        this.downloadLoading = true
        listRef.exportExcel(`${this.projectTypeLabel}项目`).finally(() => {
          this.downloadLoading = false
        })
      }
    },
    getCountData(params) {
      const sumKeys = [
        'warranty_amount<10',
        'warranty_amount>=10 and warranty_amount<=300',
        'warranty_amount>300 and warranty_amount<=1000',
        'warranty_amount>1000',
      ]
      const groupFunc = sumKeys
        .reduce((a, b) => {
          a.push(
            `sum(case when ${b} then 1 else 0 end),round(sum(case when ${b} then warranty_amount else 0 end)|2)`
          )
          return a
        }, [])
        .join(',')
      const tableName = 'market_project'
      return this.$api.getData(this.$serviceName, tableName, {
        isBIQuery: 1,
        groupFunc,
        ...getParams({ ...params, fundsType: -1 }),
      })
    },
    getResultData(res) {
      return (res && res.data && res.data.length && res.data[0]) || {}
    },
    getOptionItem(data, colors, labels) {
      let sum = 0
      const item = colors.reduce((p, c, i) => {
        const value = data[`p${i * 2 + 1}`] || 0
        sum += value
        p.push({
          name: labels[i],
          value,
          count: data[`p${i * 2 || ''}`] || 0,
          itemStyle: { color: c },
          percent: 0,
        })
        return p
      }, [])
      item.forEach(item => {
        item.percent = sum ? Math.round((item.value / sum) * 1e4) / 1e2 : '-'
      })
      return item
    },
    async getData() {
      this.loading = true
      const labels = ['10万元以下', '10(含)~300(含)万元', '300~1000(含)万元', '1000万元以上']
      const colors = [
        '#00d2d3',
        '#1dd1a1',
        '#48dbfb',
        '#54a0ff',
        '#7f8fa6',
        '#9c88ff',
        '#48dbfb',
        '#54a0ff',
        '#3498db',
        '#2ecc71',
        '#95a5a6',
        '#f1c40f',
        '#e67e22',
        '#e74c3c',
        '#f1c40f',
        '#9b59b6',
      ]
      let aData = {}
      let bData = {}
      let cData = {}
      let dData = {}
      Promise.all([
        this.getCountData(this.newQueryParams),
        this.getCountData(this.inQueryParams),
        this.getCountData(this.outQueryParams),
        this.getCountData(this.comQueryParams),
      ])
        .then(([newData, inData, outData, comData]) => {
          aData = newData
          bData = inData
          cData = outData
          dData = comData
        })
        .finally(() => {
          const { startDate, endDate } = this.queryParams
          const startYear = startDate.getFullYear()
          const startMonth = startDate.getMonth() + 1
          const endYear = endDate.getFullYear()
          const endMonth = endDate.getMonth() + 1
          this.setOption({
            aData: this.getOptionItem(this.getResultData(aData), colors.splice(0, 4), labels),
            bData: this.getOptionItem(this.getResultData(bData), colors.splice(0, 4), labels),
            cData: this.getOptionItem(this.getResultData(cData), colors.splice(0, 4), labels),
            dData: this.getOptionItem(this.getResultData(dData), colors.splice(0, 4), labels),
            subtext: `${startYear}年${startMonth}月~${endYear}年${endMonth}月`,
          })
          this.loading = false
        })
    },
    handleQuery() {
      const { dateRange } = this.formData

      // 时间处理
      if (!dateRange) {
        this.setDateParams()
      } else {
        this.queryParams.startDate = dateRange[0]
        this.queryParams.endDate = getMonthLastDayDate(
          dateRange[1].getFullYear(),
          dateRange[1].getMonth()
        )
      }

      this.getData()
    },
    handleDateQuery() {
      if (!this.queryParams.endDate) {
        this.queryParams.endDate = new Date()
      }
      this.setDateParams(this.queryParams.endDate)
      this.getData()
    },

    handleSearchClose(index) {
      switch (index) {
        case 0:
          this.inProjectSearch = ''
          this.inProjectFunds = -1
          break
        case 1:
          this.outProjectSearch = ''
          this.outProjectFunds = -1
          break
        case 2:
          this.newProjectSearch = ''
          this.newProjectFunds = -1
          break
        case 3:
          this.comProjectSearch = ''
          this.comProjectFunds = -1
          break
        default:
          break
      }
    },

    handleChartInit(chart) {
      this.chart = chart
      this.chart.on('click', ({ seriesIndex, seriesName, name, dataIndex }) => {
        // if (seriesIndex > 2) return
        this.projectType = seriesIndex
        switch (seriesIndex) {
          case 0:
            this.inProjectSearch = name + seriesName
            this.inProjectFunds = dataIndex
            break
          case 1:
            this.outProjectSearch = name + seriesName
            this.outProjectFunds = dataIndex
            break
          case 2:
            this.newProjectSearch = name + seriesName
            this.newProjectFunds = dataIndex
            break
          case 3:
            this.comProjectSearch = name + seriesName
            this.comProjectFunds = dataIndex
            break
          default:
            break
        }
      })
    },
    setOption(data) {
      this.chartOption = {
        title: [
          {
            text: data.subtext,
            top: 0,
            textStyle: {
              fontSize: 16,
            },
          },
          {
            subtext: '点击饼图可查询对应分类的详情数据',
            top: 10,
            subtextStyle: {
              fontSize: 14,
            },
          },
          {
            subtext: '新增项目金额占比',
            left: '25%',
            top: '10%',
            textAlign: 'center',
          },
          {
            subtext: '在保项目金额占比',
            left: '75%',
            top: '10%',
            textAlign: 'center',
          },
          {
            subtext: '解保项目金额占比',
            left: '25%',
            top: '52%',
            textAlign: 'center',
          },
          {
            subtext: '代偿项目金额占比',
            left: '75%',
            top: '52%',
            textAlign: 'center',
          },
        ],
        grid: {
          top: 80,
          left: 50,
          right: 80,
          bottom: 80,
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: {
              show: true,
              readOnly: true,
              optionToContent: opt => {
                const { series } = opt
                let table = `<table class="table table-bordered table-sm table-vertical-middle"><tbody>
                  <tr class="font-weight-bold">
                    <td class="text-center">报表类型</td>
                    <td>金额分类</td>
                    <td class="text-right">项目总数（个）</td>
                    <td class="text-right">总金额（万元）</td>
                    <td class="text-right">金额占比（%）</td>
                  </tr>`
                for (const serie of series) {
                  for (let j = 0; j < 4; j++) {
                    let tr = '<tr>'
                    if (j === 0) {
                      tr += `<td rowspan="4" class="text-center">${serie.name}</td>`
                    }
                    tr += `<td>${serie.data[j].name}</td>`
                    tr += `<td class="text-right">${serie.data[j].count}</td>`
                    tr += `<td class="text-right">${serie.data[j].value}</td>`
                    tr += `<td class="text-right">${serie.data[j].percent}</td>`
                    tr += '</tr>'
                    table += tr
                  }
                }
                table += `</tbody></table>`
                return table
              },
            },
            contentToOption: () => {},
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            const enumChartType = ['在保项目', '解保项目', '新增项目', '代偿项目']
            const typeName = enumChartType[params.seriesIndex]
            return `${typeName} [${params.name}]：<br>
            <div style="margin-left:1rem;">共 ${params.data.count} 个项目，累计 ${params.value} 万元，金额占比 ${params.percent}%</div>`
          },
        },
        series: [
          {
            name: '在保项目',
            type: 'pie',
            radius: '23%',
            center: ['75%', '35%'],
            data: data.bData,
            label: {
              formatter: '{b}: {d}%',
            },
            markLine: {
              silent: true,
              lineStyle: {
                type: 'solid',
                color: '#eeeeee',
              },
              symbol: ['none', 'none'],
              data: [
                [
                  { x: '50%', y: '10%' },
                  { x: '50%', y: '90%' },
                ],
              ],
            },
          },
          {
            name: '解保项目',
            type: 'pie',
            radius: '23%',
            center: ['25%', '75%'],
            data: data.cData,
            label: {
              formatter: '{b}: {d}%',
            },
          },
          {
            name: '新增项目',
            type: 'pie',
            radius: '23%',
            center: ['25%', '35%'],
            data: data.aData,
            label: {
              formatter: '{b}: {d}%',
            },
            markLine: {
              silent: true,
              lineStyle: {
                type: 'solid',
                color: '#eeeeee',
              },
              symbol: ['none', 'none'],
              data: [
                [
                  { x: '10%', y: '52%' },
                  { x: '90%', y: '52%' },
                ],
              ],
            },
          },
          {
            name: '代偿项目',
            type: 'pie',
            radius: '23%',
            center: ['75%', '75%'],
            data: data.dData,
            label: {
              formatter: '{b}: {d}%',
            },
          },
        ],
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import './analy.scss';
</style>
